package com.smartfactory.sail.controller;


import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.ada.base.common.ResultData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartfactory.sail.config.HeaderWrapper;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.constant.header.CustContactsEnum;
import com.smartfactory.sail.constant.header.CustEnum;
import com.smartfactory.sail.constant.header.SuppliersEnum;
import com.smartfactory.sail.dto.GetOrderItemByCustId;
import com.smartfactory.sail.entity.*;
import com.smartfactory.sail.entity.enums.CustContactStatusEnum;
import com.smartfactory.sail.entity.enums.CustTypeEnum;
import com.smartfactory.sail.service.*;
import com.smartfactory.sail.utils.DateUtils;
import com.smartfactory.sail.vo.PageParam;
import com.smartfactory.sail.vo.cust.*;
import com.smartfactory.sail.vo.purchase.StatisticsPurchaseByCustResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 客户信息 前端控制器
 * </p>
 *
 * @author 王巨壁
 * @since 2019-07-24
 */
@Api(tags = "客户相关")
@RestController
@RequestMapping("/cust")
public class CustController extends ControllerResponse {
    private ICustService iCustService;
    private ICustContactsService iCustContactsService;
    private ICustCareInfoService iCustCareInfoService;
    private IPurchaseRecordService iPurchaseRecordService;
    private IOrderItemService iOrderItemService;

    public CustController(ICustService iCustService, ICustContactsService iCustContactsService, ICustCareInfoService iCustCareInfoService, IPurchaseRecordService iPurchaseRecordService, IOrderItemService iOrderItemService) {
        this.iCustService = iCustService;
        this.iCustContactsService = iCustContactsService;
        this.iCustCareInfoService = iCustCareInfoService;
        this.iPurchaseRecordService = iPurchaseRecordService;
        this.iOrderItemService = iOrderItemService;
    }

    @OperRecord(content = "新增外部公司")
    @PostMapping("addCust")
    @ApiOperation(value = "客户|供应商|外发新增", notes = "客户|供应商|外发新增")
    public ApiResponse<Long> addCust(@Validated @RequestBody AddCustReq req) throws JsonProcessingException {
        Cust cust = new Cust();
        BeanUtils.copyProperties(req, cust);
        cust.setCareNum(0);//关怀次数初始为0
        if (req.getContactsInfoMap() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String contacts = objectMapper.writeValueAsString(req.getContactsInfoMap());
            cust.setContactsInfo(contacts);
        }
        //获取最近合作时间
        @NotBlank String firstCooperationTime = req.getFirstCooperationTime();
        String today = DateUtils.getNowDate();
        Long betweenDate = DateUtils.dayDiff(firstCooperationTime, today);
        if (req.getCustType() == CustTypeEnum.GYS.getCode()) {
            cust.setCustType(CustTypeEnum.GYS);
        } else if (req.getCustType() == CustTypeEnum.WFQY.getCode()) {
            cust.setCustType(CustTypeEnum.WFQY);
        } else {
            cust.setCustType(CustTypeEnum.DDKH);
        }
        cust.setCooperationDuration(betweenDate + "天");
        if (iCustService.save(cust))
            return ok(cust.getId());
        return fail(ResultData.FAIL_CODE_MSG);
    }


    @PostMapping("updateCust")
    @ApiOperation(value = "客户|供应商|外发新增", notes = "客户|供应商|外发新增")
    public ApiResponse<Long> updateCust(@Validated @RequestBody UpdateCustReq req) throws JsonProcessingException {
        Cust cust = new Cust();
        BeanUtils.copyProperties(req, cust);
        if (req.getContactsInfoMap() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String contacts = objectMapper.writeValueAsString(req.getContactsInfoMap());
            cust.setContactsInfo(contacts);
        }
        //获取最近合作时间
        @NotBlank String firstCooperationTime = req.getFirstCooperationTime();
        String today = DateUtils.getNowDate();
        Long betweenDate = DateUtils.dayDiff(firstCooperationTime, today);
        cust.setCooperationDuration(betweenDate + "天");
        if (iCustService.updateById(cust))
            return ok(cust.getId());
        return fail(ResultData.FAIL_CODE_MSG);
    }

    @OperRecord(content = "添加关怀人")
    @PostMapping("addContacts")
    @ApiOperation(value = "添加关怀人", notes = "添加关怀人")
    public ApiResponse<Long> addContacts(@RequestBody AddCustContactsReq req) throws JsonProcessingException {
        CustContacts custContacts = new CustContacts();
        BeanUtils.copyProperties(req, custContacts);
       /* CustCareInfo custCareInfo = new CustCareInfo();
        BeanUtils.copyProperties(req, custCareInfo);*/
        if (req.getContactsInfoMap() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String contacts = objectMapper.writeValueAsString(req.getContactsInfoMap());
            custContacts.setContactsInfo(contacts);
        }
        //设置最近一次关怀时间
        //custContacts.setLastTime(DateUtils.getNowDay());
        //设置状态为正常
        custContacts.setStatus(CustContactStatusEnum.ZC);

        //设置关怀时间
        //custCareInfo.setCareTime(DateUtils.getNowDay());
        //保存联系人同时需要保存关怀的信息
        if (iCustContactsService.save(custContacts)) {

                return ok(custContacts.getId());
        }
        return fail(ResultData.FAIL_CODE_MSG);
    }

    @OperRecord(content = "添加关怀记录")
    @PostMapping("addCareInfo")
    @ApiOperation(value = "添加关怀", notes = "添加关怀")
    public ApiResponse<Object> listContacts(@RequestBody CustCareInfo custCareInfo) {
        if (iCustCareInfoService.save(custCareInfo)) {
            CustContacts custContacts = new CustContacts();
            custContacts.setLastTime(DateUtils.getNowDay());
            custContacts.setId(custCareInfo.getContactsId());
            iCustContactsService.updateById(custContacts);
            return ok();
        }
        return fail("关怀失败!");
    }

    //---------------客户联系人----------------------------------------------------------------------
    @HeaderWrapper(CustContactsEnum.class)
    @PostMapping("listContacts/{currentPage}/{size}/{sortType}/{sortField}")
    @ApiOperation(value = "客户关怀列表", notes = "客户联系人列表")
    public ApiResponse<IPage<ListContactsResp>> listContacts(@RequestBody Map<String, Object> queryParam,
                                                             @PathVariable("currentPage") Long currentPage,
                                                             @PathVariable("size") Integer size,
                                                             @PathVariable("sortType") Integer sortType,
                                                             @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iCustContactsService.getCustContactsListPage(queryParam, pageParam));
    }

    @GetMapping("custContactsInfo/{id}")
    @ApiOperation(value = "根据联系人id获取客户联系人详情", notes = "根据联系人id获取客户联系人详情")
    public ApiResponse<Object> getCustContactsInfoById(@PathVariable("id") Long id) {
        return ok(iCustContactsService.getById(id));
    }

    @GetMapping("custCareList/{contactsId}")
    @ApiOperation(value = "根据联系人id获取关怀列表详情", notes = "根据联系人id获取关怀列表详情")
    public ApiResponse<Object> getCustCareListByContactsId(@PathVariable("contactsId") Long id) {
        QueryWrapper<CustCareInfo> query = new QueryWrapper<>();
        query.orderByDesc("updateTime");
        query.eq("contactsId", id);
        return ok(iCustCareInfoService.list(query));
    }
    @OperRecord(content = "添加关怀记录")
    @PostMapping("addCareInfoList")
    @ApiOperation(value = "批量保存关怀信息", notes = "批量保存关怀信息")
    public ApiResponse<Object> addCareInfoBatch(@RequestBody List<CustCareInfo> careInfos) {
        if (iCustCareInfoService.saveBatch(careInfos)) {
            return ok();
        }
        return fail("保存关怀失败");
    }


    @PostMapping("updateContacts")
    @ApiOperation(value = "根据联系人id修改信息", notes = "根据联系人id修改信息")
    public ApiResponse<Object> updateContacts(@RequestBody CustContacts custContacts) throws JsonProcessingException {
        if (custContacts.getContactsInfoMap() != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String contacts = objectMapper.writeValueAsString(custContacts.getContactsInfoMap());
            custContacts.setContactsInfo(contacts);
        }
        if (iCustContactsService.updateById(custContacts)) {
            return ok();
        }
        return fail("修改联系人信息失败失败");
    }

    @GetMapping("getStatistics/{custId}")
    @ApiOperation(value = "统计联系人的关怀收益比 传custId", notes = "统计联系人的关怀收益比 传custId")
    public ApiResponse<Object> getStatistics(@PathVariable("custId") Long custId) {
        return ok(iCustContactsService.getStatistics(custId));
    }

    @GetMapping("getCooperationCompanyList/{custType}")
    @ApiOperation(value = "获取所有合作企业的列表1.交易客户2,供应商3外发企业", notes = "获取所有合作企业的列表1.交易客户2,供应商3外发企业")
    public ApiResponse<Object> getCooperationCompanyList(@PathVariable("custType") Integer custType) {
        QueryWrapper<Cust> query = new QueryWrapper<>();
        query.eq("custType", custType);
        query.eq("custType", custType);
        return ok(iCustService.list(query));
    }

    @HeaderWrapper(SuppliersEnum.class)
    @PostMapping("listSuppliers/{currentPage}/{size}/{sortType}/{sortField}")
    @ApiOperation(value = "获取所有供货商列表", notes = "获取所有供货商列表")
    public ApiResponse<Object> listSuppliers(@RequestBody Map<String, Object> queryParam,
                                                                @PathVariable("currentPage") Long currentPage,
                                                                @PathVariable("size") Integer size,
                                                                @PathVariable("sortType") Integer sortType,
                                                                @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iCustService.listSuppliers(queryParam, pageParam));
    }

    @HeaderWrapper(CustEnum.class)
    @PostMapping("listCust/{currentPage}/{size}/{sortType}/{sortField}")
    @ApiOperation(value = "获取客户列表", notes = "获取客户列表")
    public ApiResponse<Object> listCust(@RequestBody Map<String, Object> queryParam,
                                             @PathVariable("currentPage") Long currentPage,
                                             @PathVariable("size") Integer size,
                                             @PathVariable("sortType") Integer sortType,
                                             @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iCustService.listCust(queryParam, pageParam));
    }

    @GetMapping("supplierInfoById/{custId}")
    @ApiOperation(value = "根据id获取供应商详情", notes = "根据id获取供应商详情")
    public ApiResponse<SupplierInfoResp> supplierInfoById(@PathVariable("custId") Long custId) {
        Cust byId = iCustService.getById(custId);

        if (byId != null) {
            String firstCooperationTime = byId.getFirstCooperationTime();
            String today = DateUtils.getNowDate();
            if (firstCooperationTime != null) {
                Long betweenDate = DateUtils.dayDiff(firstCooperationTime, today);
                byId.setCooperationDuration(betweenDate + "天");
            } else {
                byId.setCooperationDuration("/");
            }
            SupplierInfoResp supplierInfoResp = new SupplierInfoResp();
            BeanUtils.copyProperties(byId,supplierInfoResp);
            //查询合作记录
            QueryWrapper<PurchaseRecord> purchaseQuery = new QueryWrapper<>();
            purchaseQuery.eq("supplierId", custId);
            purchaseQuery.ne("status", 1);//必须是确定采购单的才会有custId
            purchaseQuery.select("updateTime", "itemName", "itemId", "itemCode", "purchaseSize", "currentPrice");
            List<PurchaseRecord> list = iPurchaseRecordService.list(purchaseQuery);
            List<StatisticsPurchaseByCustResp> statisByCustId = iPurchaseRecordService.getStatisByCustId(custId);
            supplierInfoResp.setList(list);
            supplierInfoResp.setStatisByCustId(statisByCustId);
            iCustService.updateById(byId);
            return ok(supplierInfoResp);
        } else {
            return fail("该供应商不存在");
        }
    }

    @GetMapping("custInfo/{custId}")
    @ApiOperation(value = "根据id获取客户详情", notes = "根据id获取客户详情")
    public ApiResponse<CustInfoResp> custInfoById(@PathVariable("custId") Long custId) {
        Cust byId = iCustService.getById(custId);

        if (byId != null) {
            String firstCooperationTime = byId.getFirstCooperationTime();
            String today = DateUtils.getNowDate();
            if (firstCooperationTime != null) {
                Long betweenDate = DateUtils.dayDiff(firstCooperationTime, today);
                byId.setCooperationDuration(betweenDate + "天");
            } else {
                byId.setCooperationDuration("/");
            }

            CustInfoResp custInfoResp = new CustInfoResp();
            BeanUtils.copyProperties(byId,custInfoResp);
            iCustService.updateById(byId);
            //查询合作记录
            List<GetOrderItemByCustId> orderItemByCustId = iOrderItemService.getOrderItemByCustId(custId);
            custInfoResp.setList(orderItemByCustId);
            return ok(custInfoResp);
        } else {
            return fail("该供应商不存在");
        }
    }

}
